import json

from channels.layers import get_channel_layer # AsyncWebsocketConsumer已经实现了这个函数
from channels.generic.websocket import AsyncWebsocketConsumer

class MessagesConsumer(AsyncWebsocketConsumer):
    """处理私信应用中的websocket请求"""

    async def connect(self):
        if self.scope['user'].is_anonymous:
            # 匿名用户拒绝连接
            await self.close()
        else:
            # 加入聊天组----> 组 / 频道
            await self.channel_layer.group_add(self.scope['user'].username,self.channel_name)
            await self.accept()

    async  def receive(self, text_data=None, bytes_data=None):
        """接收私信"""
        await self.send(text_data = json.dumps(text_data))

    async def disconnect(self, code):
        """离开聊天组"""
        await self.channel_layer.group_discard(self.scope['user'].username,self.channel_name)







"""
# Generic Consumers同步与异步通信
from channels.generic.websocket import WebsocketConsumer,AsyncWebsocketConsumer

class MyConsumer(WebsocketConsumer):

    def connect(self):
        self.accept(subprotocol='you protocol') # 自定义的子协议
        self.close(code=403)

    def receive(self, text_data=None, bytes_data=None):
        self.send(text_data="imooc.com")  # 文本数据
        self.send(bytes_data="imooc.com")  #把字符串转换为二进制的帧

        self.close()

    def disconnect(self, code):
        pass


class MyAsyncConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        await self.accept(subprotocol='you protocol')  # 自定义的子协议
        await self.close(code=403)

    async def receive(self, text_data=None, bytes_data=None):
        await self.send(text_data="imooc.com")  # 文本数据
        await self.send(bytes_data="imooc.com")  # 把字符串转换为二进制的帧

        await self.close()

    async def disconnect(self, code):
        pass
"""
